<script setup>
import {ref,onMounted,onUnmounted} from 'vue'

import PostItem from "@/components/PostItem.vue";
import UserLayout from "@/views/user/UserLayout.vue";
import {getFollowPostService} from "@/api/post.js";

const pageNum = ref(1)
const pageSize = ref(6)
const hasMore = ref(true)
const isLoading = ref(false)
const isRefreshing = ref(false)
const pullDistance = ref(0)


const posts = ref([
])
const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};
const getPosts = async () =>{
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  try {
    const res = await getFollowPostService(pageNum.value,pageSize.value)
    if(posts.value.length>0){
      await sleep(500);
    }
    if (isRefreshing.value) {
      posts.value = res.data.data;
    } else {
      posts.value = [...posts.value, ...res.data.data];
    }
    hasMore.value = res.data.data.length >= pageSize.value;
    console.log("结果："+posts.value.length+" "+hasMore.value)
    pageNum.value++;
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
    pullDistance.value = 0;
  }
}
getPosts()


const handleScroll = () => {
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  console.log("////")
  if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading.value) {
    console.log(".....")
    getPosts()
  }
};

// 在挂载时添加监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

// 卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

// 处理点赞
const handleLike = ({id, liked}) => {
  const post = posts.value.find(p => p.id === id)
  if (post) {
    post.likes += liked ? 1 : -1
    post.liked = liked
  }
}
// 切换展开状态
const toggleExpand = (postId) => {
  const post = posts.value.find(p => p.id === postId)
  if (post) post.expanded = !post.expanded
}
</script>

<template>
  <UserLayout>
    <!-- 文章详情内容 -->
    <div class="post-container" @scroll="handleScroll">
      <PostItem
        v-for="post in posts"
        :key="post.id"
        :post="post"
        @like="handleLike"
        @toggle-expand="toggleExpand"
      />
    </div>
    <div v-if="isLoading" class="loading-tip">加载中...</div>
    <div v-if="!hasMore" class="nomore-tip">没有更多内容了</div>
  </UserLayout>
</template>

<style scoped lang="scss">
.loading-tip, .nomore-tip {
  text-align: center;
  padding: 20px;
  color: #666;
}
.post-container{

  overflow-y: auto;
}
.post-container::-webkit-scrollbar {
  width: 0;
  background: transparent;
}
</style>
